package org.sword.wechat4j.common;

import java.io.File;

import org.apache.commons.lang3.StringUtils;
import org.sword.lang.HttpUtils;
import org.sword.wechat4j.exception.WeChatException;
import org.sword.wechat4j.response.ArticleResponse;
import org.sword.wechat4j.token.TokenProxy;
import org.sword.wechat4j.util.WeChatUtil;

import com.alibaba.fastjson.JSONObject;

public class MediaFile {
	/**
	 * 上传临时普通素材
	 */
	private static final String UPLOAD = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=";
	
	/**
	 * 上传图文消息内容图片素材
	 */
	private static final String UPLOADIMAGER = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=";
	
	/**
	 * 上传临时图文素材
	 */
	private static final String UPLOADMAPNEWS = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=";
	/**
	 * 下载临时普通素材
	 */
	private static final String DOWNLOAD = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=";
	private static final String PARAM_FILE = "media";
	private static final String PARAM_MEDIA_ID = "media_id";
	private static final String PARAM_TYPE = "type";
	private static final String PARAM_CREATE_TIME = "created_at";
	private MediaType type;
	private File file;
	private String mediaId;
	private String createdTimestamp;

	/**
	 * 设置上传临时素材链接
	 * @return
	 */
	private String uploadUrl() {
		String url = UPLOAD + TokenProxy.accessToken() + "&" + PARAM_TYPE + "="
				+ this.type.name();
		return url;
	}
	
	/**
	 * 设置上传图文消息内容图片链接
	 * @return
	 */
	private String uploadImagerUrl() {
		String url = UPLOADIMAGER + TokenProxy.accessToken();
		return url;
	}
	
	/**
	 * 设置上传临时图文素材链接
	 * @return
	 */
	private String uploadMapnewsUrl() {
		String url = UPLOADMAPNEWS + TokenProxy.accessToken();
		return url;
	}

	private String downloadUrl() {
		String url = DOWNLOAD + TokenProxy.accessToken() + "&" + PARAM_MEDIA_ID
				+ "=" + this.mediaId;
		return url;
	}

	/**
	 * 上传临时素材
	 * 
	 * @param file
	 * @param type
	 * @return
	 */
	public String upload(File file, MediaType type) {
		this.file = file;
		this.type = type;
		String url = uploadUrl();
		String result = HttpUtils.postFile(url, PARAM_FILE, file);
		parseUploadResult(result);
		if (StringUtils.isNotBlank(this.mediaId))
			return this.mediaId;
		return null;
	}
	
	/**
	 * 只上传图片，上传图文消息内容图片素材，返回图片访问链接
	 * @param file
	 * @return 返回图片访问链接
	 * @throws WeChatException
	 */
	public String uploadImager(File file) throws WeChatException {
		this.file = file;
		String url = uploadImagerUrl();
		String result = HttpUtils.postFile(url, PARAM_FILE, file);
		WeChatUtil.isSuccess(result);
		JSONObject jsonObject = JSONObject.parseObject(result);
		String resultUrl = (String) jsonObject.get("url");
		if (StringUtils.isNotBlank(resultUrl))
			return resultUrl;
		return null;
	}

	/**
	 * 上传临时图文素材
	 * @param articles
	 * @return
	 */
	public String uploadMapnews(ArticleResponse[] articles, MediaType type) {
		JSONObject jsonArticles = new JSONObject();
		this.type = type;
		jsonArticles.put("articles", articles);
		System.out.println(jsonArticles.toJSONString());
		String url = uploadMapnewsUrl();
		String result = HttpUtils.post(url, jsonArticles.toJSONString());
		parseUploadResult(result);
		if (StringUtils.isNotBlank(this.mediaId))
			return this.mediaId;
		return null;
	}
	
	/**
	 * 返回结果
	 * {"type":"voice","media_id":"eo0_qqIvGKzxwklT65WdTXYLXZ3jqUTtAL8ZBdIrz-wZ-e8KrkVJav4z8OuHkn_r","created_at":1439353484}
	 * {"type":"video","media_id":"iJpf45plOl5GjoG8HlNF2VFSY6a5QihduF9DNZjIeXd_X1lg_LPdSxgJqf6wcZnE","created_at":1439353780}
	 * {"type":"thumb","thumb_media_id":"g-xhTsrKhDOfQUopd1QA_K8pSWSFhfMwNnMW7pxqtVy-kyTC4EnVZiISe31eTxRQ","created_at":1439353824}
	 * {"type":"image","media_id":"Ip0Oi6fbrY6_Fc18CGjFFPpZJu4pFF9PwcnoD2lqQ3uxNeF04G4SEI-hK9KUzCaR","created_at":1439353850}
	 * @param result
	 */
	private void parseUploadResult(String result) {
		try {
			WeChatUtil.isSuccess(result);
			JSONObject jsonObject = JSONObject.parseObject(result);
			this.createdTimestamp = jsonObject.getString(PARAM_CREATE_TIME);
			switch (this.type) {
				case thumb:
					this.mediaId = jsonObject.getString("thumb_media_id");
					break;
				default:
					this.mediaId = jsonObject.getString(PARAM_MEDIA_ID);
					break;
			}
		} catch (WeChatException e) {
			this.mediaId = null;
			this.createdTimestamp = null;
			e.printStackTrace();
		}
	}
	
	public byte[] download(String mediaId) {
		this.mediaId = mediaId;
		String url = downloadUrl();
		byte[] fb = HttpUtils.getFile(url);
		if ((fb == null) || (fb.length == 0))
			return null;
		return fb;
	}

	public MediaType getType() {
		return this.type;
	}

	public String getMediaId() {
		return this.mediaId;
	}

	public String getCreatedTimestamp() {
		return this.createdTimestamp;
	}
}